package com.xm.linxiaogang.network.interceptor

import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import kotlin.Throws

/**
 * 请求拦截器
 * 可以在接口发起请求时，统一做些处理，例如添加请求头参数、重构请求体参数等等
 */
class RequestInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val builder = chain.request().newBuilder()
        val request = chain.request()

        //1.添加请求头参数（如果没有需要可以删掉）
        builder.addHeader("token", "")
        builder.addHeader("device", "android")

        //2.重构请求体参数（如果没有需要可以删掉）
        if (request.body() is FormBody) {//表单请求
            val newFormBody = FormBody.Builder() //定义新的请求体
            val oldFormBody = request.body() as FormBody //获取旧的请求体
            for (i in 0 until oldFormBody.size()) {
                val key = oldFormBody.encodedName(i)
                val value = oldFormBody.encodedValue(i)
                newFormBody.addEncoded(key, value)
            }
            //统一添加时间戳
            newFormBody.addEncoded("timestamp", System.currentTimeMillis().toString())
            builder.method(request.method(), newFormBody.build()) //设置新的请求体
        } else {//url请求
            val httpUrl = request.url()
                .newBuilder()
                .addQueryParameter("timestamp", System.currentTimeMillis().toString())//统一添加时间戳
                .build()
            builder.url(httpUrl)
        }
        return chain.proceed(builder.build())
    }

}